package cn.ygh.bbo.system.service.impl;

import cn.ygh.bbo.system.bean.AdminRole;
import cn.ygh.bbo.system.service.AdminRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import cn.ygh.bbo.framerwork.core.Grid;
import cn.ygh.bbo.common.exception.TipException;
import cn.ygh.bbo.common.annotation.DataScope;
import cn.ygh.bbo.system.bean.Admin;
import cn.ygh.bbo.system.mapper.AdminMapper;
import cn.ygh.bbo.system.service.AdminService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

/**
 * 描述：管理员  ServiceImpl
 * @author ygh
 */
@Service
public class AdminServiceImpl implements AdminService{

    private final Logger logger=LoggerFactory.getLogger(getClass());

    @Autowired
    AdminMapper mapper;

    @Autowired
    AdminRoleService adminRoleService;

    /**
    * 保存对象
    * @param  admin 对象信息
    * @return
    */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int save(Admin admin) {
        //保存之前通用处理
        beforeCreate(admin);
        admin.def();
        return mapper.insert(admin);
    }

    /**
    * 更新对象
    * @param  admin 对象信息
    * @return
    */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int update(Admin admin) {
        if(admin.getId()==null){
            throw new TipException("id can not null");
        }
        //更新之前通用处理
        beforeUpdate(admin);
        admin.def();
        return mapper.updateById(admin);
    }

    /**
    * 批量更新
    * @param  admin 对象信息
    * @param ids
    * @return
    */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateBatchByIds(Admin admin, Serializable[] ids) {
        if(ids==null || ids.length==0){
            throw new TipException("ids can not null");
        }
        return mapper.updateBatchByIds(admin,ids);
    }

    /**
    * 根据ID删除对象
    * @param id
    * @return
    */
    @Override
    public int deleteById(Serializable id) {
        if(id==null){
            throw new TipException("id can not null");
        }
        if(checkLink(id)){
            return mapper.deleteById(id);
        }
        return 0;
    }

    /**
    * 删除关联判断
    * @param id
    */
    private boolean checkLink(Serializable id) {
        Integer i=Integer.valueOf(id.toString());
        long count=adminRoleService.getCountByAdminIdAndRoleId(i, null);
        if (count>0){
            throw new TipException(String.format("角色相关还存在%s条数据,无法删除",count));
        }
        return true;
    }

    /**
    * 根据ID数组批量删除对象
    * @param ids
    * @return
    */
    @Override
    public int deleteByIds(Serializable[] ids) {
        if(ids==null || ids.length==0){
            throw new TipException("ids can not null");
        }
        int result=0;
        for (Serializable id:ids){
            result+=deleteById(id);
        }
        return result;
    }

    /**
    * 根据ID获取对象
    * @param id
    * @return
    */
    @Override
    public Admin getById(Serializable id) {
        if(id==null){
            throw new TipException("id can not null");
        }
        return mapper.selectById(id);
    }

    /**
    * 根据ID数组获取对象列表
    * @param ids
    * @return
    */
    @Override
    public List<Admin> listfindByIn(Serializable[] ids) {
        if(ids==null || ids.length==0){
            throw new TipException("ids can not null");
        }
        return mapper.selectBatchIds(Arrays.asList(ids));
    }

    /**
    * 根据对象信息获取满足条件的对象列表
    * @param  admin 对象信息
    * @param pageable 分页条件为空则不分页
    * @return
    */
    @DataScope
    @Override
    public List<Admin> listfind(Admin admin, Pageable pageable) {
        if (pageable!=null && pageable.getPageNumber()!=0){
            PageHelper.startPage(pageable.getPageNumber()
                    , pageable.getPageSize(), false);
        }
        return mapper.selectByObj(admin);
    }

    /**
    * 根据对象信息获取满足条件的对象列表和总数
    * @param  admin 对象信息
    * @param pageable 分页条件
    * @return
    */
    @DataScope
    @Override
    public Grid listGrid(Admin admin, Pageable pageable) {
        PageHelper.startPage(pageable.getPageNumber()
                , pageable.getPageSize(), true);
        List<Admin> admins = mapper.selectByObj(admin);
        PageInfo<Admin>pageInfo=new PageInfo<>(admins);
        Grid grid=new Grid();
        grid.setTotal((int) pageInfo.getTotal());
        grid.setRows(pageInfo.getList());
        return grid;
    }

    /**
     * 通过username获取对象
     *
     * @param username
     * @return
     */
    @Override
    public Admin getByUsername(String username) {
        Admin params=new Admin();
        params.setUsername(username);
        List<Admin>admins=listfind(params,PageRequest.of(1, 1));
        if (admins.size()>0){
            return admins.get(0);
        }
        return null;
    }

    /**
     * 刷新管理员的角色
     *
     * @param adminId
     * @param roleIds
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void createRoles(Integer adminId, String roleIds) {
        //先删除之前的角色
        adminRoleService.deleteByAdminId(adminId);
        if (StringUtils.isBlank(roleIds)){
            return;
        }
        //重新创建角色列表
        String []ids=roleIds.split(",");
        for (String id:ids){
            AdminRole adminRole = new AdminRole(
                    Integer.parseInt(id) //角色序号
                    ,adminId //管理员序号
            );
            adminRoleService.save(adminRole);
        }
    }

    /**
     * 获取部门下的管理员数量
     *
     * @param deptId
     * @return
     */
    @Override
    public long getCountByDeptId(Integer deptId) {
        Admin params=new Admin();
        params.setDeptId(deptId);
        return mapper.selectCountByObj(params);
    }
}
